package com.ekingstar.framework.service.impl;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.ekingstar.framework.domain.Role;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.domain.UserRole;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.service.IUserRoleService;

public class UserRoleServiceImpl implements IUserRoleService{

	private static Logger log = LoggerFactory.getLogger(UserRoleServiceImpl.class);
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	public boolean userAddRole(String uid,List<Role> hasroles){
		final String fuid = uid;
		final User user = UserUtil.getCurrentUser();
		if(user == null){
			return false;
		}
		if(user.getId() == null || user.getId().equals("")){
			return false;
		}
		this.hibernateTemplate.execute(new HibernateCallback(){
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Query q = session.createQuery(" update UserRole a set a.deleteDate = :now ,a.deleterId=:uId where a.TUser.id = :id");
				q.setParameter("now", new Date());
				q.setParameter("uId", user.getId());
				q.setParameter("id", fuid);
				q.executeUpdate();
				return null;
			}
		});
		for(Role o : hasroles){
			if(hasroles == null || hasroles.equals("")){
				continue;
			}
			UserRole ur = new UserRole();
			User tu = new User();
			tu.setId(fuid);
			ur.setTRole(o);
			ur.setTUser(tu);
			ur.setAdderId(user.getId());
			ur.setAddDate(new Date());
			ur.setCanGrant(o.getCanGrant());
			ur.setCanUse(o.getCanUse());
			if(o.getCanGrant().equals(false)&&o.getCanUse().equals(false)){
				continue;
			}
			this.hibernateTemplate.save(ur);
		}
		return true;
	}
}
